package com.yue.lin.controller;

import com.yue.lin.domain.Permission;
import com.yue.lin.domain.User;
import com.yue.lin.service.ILoginService;
import com.yue.lin.service.PermissionService;
import com.yue.lin.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
public class LoginResource {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private UserService userService;

    @GetMapping("login")
    public String login() {
        return "toLogin.html";
    }

    //post登录
    @PostMapping("doLogin")
    public void login(String username, String password, HttpServletResponse response) throws IOException {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        //进行验证，这里可以捕获异常，然后返回对应信息
        try {
            subject.login(usernamePasswordToken);
            System.out.println("登录成功");
            String id = userService.current().getId();
            permissionService.deleteCache(id);
        } catch (UnknownAccountException e) {
            response.sendRedirect("/toLogin.html?error=" + URLEncoder.encode("用户名有误！", "utf-8"));
        } catch (IncorrectCredentialsException e2) {
            response.sendRedirect("/toLogin.html?error=" + URLEncoder.encode("密码有误！", "utf-8"));
        }
    }

    //注解的使用  权限不足抛出异常： Not authorized to invoke method:
    @RequiresPermissions("daily::read")
    @GetMapping(value = "/create")
    @ResponseBody
    public String create() {
        return "Create success!";
    }

    //获取当前登录用户
//    @RequiresRoles("admin")
//    @GetMapping("current")
//    public User current() {
//        return userService.current();
//    }
}